package com.cool.shark.controller;

import com.cool.shark.ex.ServiceException;
import com.cool.shark.pojo.dto.UserChangeDto;
import com.cool.shark.pojo.dto.UserDto;
import com.cool.shark.pojo.entity.User;
import com.cool.shark.service.UserService;
import com.cool.shark.web.JsonResult;
import com.cool.shark.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


/**
 * @Name: UserController
 * @Author: 西风残叶
 * @Date: 2024/3/29 20:58
 * @Version: 1.0
 * @TODO: TODO
 */
@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 添加用户信息。
     *
     * @param userDto 用户数据传输对象，包含用户详细信息，通过请求体传入。
     * @return JsonResult<Void> 返回一个空的JSON结果对象，表示操作成功。
     */
    @PostMapping("/addUser")
    public JsonResult<Void> addUser(@RequestBody UserDto userDto){
        log.info("user = " +userDto);
        userService.addUser(userDto);

        return JsonResult.ok();
    }

    @PostMapping("/login")
    public JsonResult<User> login(@RequestBody UserDto userDto){
        log.info("userDto = " +userDto);
        User login = userService.login(userDto);
        try {
            Thread.sleep(1000 * 3);
        } catch (InterruptedException e) {
            String message = "登录失败服务器忙";
            throw new ServiceException(ServiceCode.ERR_BAD_REQUEST, message);
        }
        return JsonResult.ok(login);
    }

    /**
     * 获取用户数量
     *
     * @return JsonResult<Integer> 返回用户数量的JSON结果，其中包含操作状态和用户数量。
     */
    @GetMapping("/getUserNum")
    public JsonResult<Integer> getUserNum(){
        Integer userNum = userService.countUsers();
        return JsonResult.ok(userNum);
    }

    @PostMapping("/change")
    public JsonResult<Void> changePassword(@RequestBody UserChangeDto userDto){
        log.info("userDto = " +userDto);
        userService.changePassword(userDto);
        return JsonResult.ok();
    }
}